package iQuizzView;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.WaitScreen;
import org.netbeans.microedition.util.SimpleCancellableTask;






//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">
/**
 * @author Athéna
 */
public class iQuizzGui extends MIDlet implements CommandListener, ItemCommandListener {

    private boolean midletPaused = false;
    //Champs pour tester à enlever éventuellement
    private String password;//Mot de passe donné par le professeur(essai)
    private int responseschoices = 5; // Nombre de choix de réponses pour chaque question (essai)
    private String[] chosenresponses;//Tableau des réponses choisies (essai)
    int index=0;//indice pour le tableau de réponses choisies(essai)
   private PhoneNI ni;
     private PhoneController ct;
     //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
     private List list;
     private Form form;
     private StringItem stringItem;
     private StringItem stringItem2;
     private TextField textField;
     private WaitScreen waitScreen;
     private Command okCommand3;
     private Command exitCommand;
     private Command okCommand1;
     private SimpleCancellableTask task;
     private Image image;
     //</editor-fold>//GEN-END:|fields|0|

    /**
     * The iQuizzGui constructor.
     */
    public iQuizzGui() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|
    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here

//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        switchDisplayable(null, getForm());
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    /*Page de connexion pour entrer le mot de passe du quizz*/
    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form("iQuizz", new Item[] { getStringItem(), getTextField(), getStringItem2() });//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getExitCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
    //</editor-fold>//GEN-END:|14-getter|2|
/*Permet d'avoir le message de bienvenue*/
    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|15-getter|0|15-preInit
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|15-getter|0|15-preInit
            // write pre-init user code here
            stringItem = new StringItem("", "Bienvenue sur iQuizz");//GEN-LINE:|15-getter|1|15-postInit
            // write post-init user code here
        }//GEN-BEGIN:|15-getter|2|
        return stringItem;
    }
    //</editor-fold>//GEN-END:|15-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|19-preAction
            if (command == exitCommand) {//GEN-END:|7-commandAction|1|19-preAction
                // Close the application
                exitMIDlet();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|71-preAction
        } else if (displayable == list) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|3|71-preAction
                //listAction() non utilisée ici
                listAction();//GEN-LINE:|7-commandAction|4|71-postAction

            } else if (command == okCommand3) {//GEN-LINE:|7-commandAction|5|77-preAction
                // Envoi des numéros sélectionnés
                int nbvotes=0;
                boolean choice[] = new boolean[list.size()];//Tableau contenant le statut de sélection des items
                chosenresponses= new String[list.size()];// Tableau qui contiendra les réponses choisies
                list.getSelectedFlags(choice);//Permet d'avoir le statut de tous les items
                for (int a = 0; a < choice.length; a++){
                     System.out.println(list.getString(a)+ choice[a]);//Affichage du statut

                     //Enregistrement dans un tableau des numéros choisis
                     if (choice[a]){
                         nbvotes++;
                         System.out.println("Enregistrement d'un numéro sélectionné");
                         chosenresponses[index]=list.getString(a);//On stocke les numéros cochés
                         System.out.println(chosenresponses[index]);
                         index=index+1;
                         if(nbvotes<= ct.getNbVote())
                         ct.sendVote(a);
                     }


                }
                index=0; //On le remet à 0 pour les questions suivantes
                //Affichage de la fenêtre de blocage
                switchDisplayable(null, getWaitScreen());//GEN-LINE:|7-commandAction|6|77-postAction

            }//GEN-BEGIN:|7-commandAction|7|53-preAction
        } else if (displayable == waitScreen) {
            if (command == WaitScreen.FAILURE_COMMAND) {//GEN-END:|7-commandAction|7|53-preAction
                System.out.println("WaitScreen Failure Command");
//GEN-LINE:|7-commandAction|8|53-postAction

            } else if (command == WaitScreen.SUCCESS_COMMAND) {//GEN-LINE:|7-commandAction|9|52-preAction
                System.out.println("WaitScreen Success Command");
                //A enlever: appeler juste pour tester si le passage de la page de blocage à la liste de réponses marche
                //Pour l'enlever,supprimez le lien dans Flow de SUCCESS_COMMAND à list
                /*
                //Invoquez cette fonction seulement lorsqu'une nouvelle question arrive
switchDisplayable (null, getList ());//GEN-LINE:|7-commandAction|10|52-postAction
*/
            }//GEN-BEGIN:|7-commandAction|11|7-postCommandAction
        }//GEN-END:|7-commandAction|11|7-postCommandAction
            // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|12|
    //</editor-fold>//GEN-END:|7-commandAction|12|








    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|18-getter|2|


    /*Commande pour valider l'entrée le mot de passe correspondant au quizz*/
    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initiliazed instance of okCommand1 component.
     * @return the initialized component instance
     */
    public Command getOkCommand1() {
        if (okCommand1 == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            okCommand1 = new Command("Ok", Command.OK, 0);//GEN-LINE:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return okCommand1;
    }
    //</editor-fold>//GEN-END:|35-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">//GEN-BEGIN:|45-getter|0|45-preInit
    /**
     * Returns an initiliazed instance of textField component.
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {//GEN-END:|45-getter|0|45-preInit
            // write pre-init user code here
            textField = new TextField("Entrez la cl\u00E9 pour le quizz", null, 32, TextField.ANY);//GEN-BEGIN:|45-getter|1|45-postInit
            textField.setPreferredSize(3, 2);
            textField.addCommand(getOkCommand1());
            textField.setItemCommandListener(this);
            textField.setDefaultCommand(getOkCommand1());
            textField.setLayout(ImageItem.LAYOUT_DEFAULT);
            textField.setInitialInputMode("UCB_BASIC_LATIN");//GEN-END:|45-getter|1|45-postInit
            // write post-init user code here
        }//GEN-BEGIN:|45-getter|2|
        return textField;
    }
    //</editor-fold>//GEN-END:|45-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem2 ">//GEN-BEGIN:|46-getter|0|46-preInit
    /**
     * Returns an initiliazed instance of stringItem2 component.
     * @return the initialized component instance
     */
    public StringItem getStringItem2() {
        if (stringItem2 == null) {//GEN-END:|46-getter|0|46-preInit
            // write pre-init user code here
            stringItem2 = new StringItem("", "Appuyez sur ok pour se connecter");//GEN-LINE:|46-getter|1|46-postInit
            // write post-init user code here
        }//GEN-BEGIN:|46-getter|2|
        return stringItem2;
    }
    //</editor-fold>//GEN-END:|46-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Items ">//GEN-BEGIN:|8-itemCommandAction|0|8-preItemCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular item.
     * @param command the Command that was invoked
     * @param displayable the Item where the command was invoked
     */
    public void commandAction(Command command, Item item) {//GEN-END:|8-itemCommandAction|0|8-preItemCommandAction
        // write pre-action user code here
        if (item == textField) {//GEN-BEGIN:|8-itemCommandAction|1|47-preAction
            if (command == okCommand1) {//GEN-END:|8-itemCommandAction|1|47-preAction
                //Récupération du mot de passe tapé
                this.password = textField.getString();
                switchDisplayable(null, getWaitScreen());//GEN-LINE:|8-itemCommandAction|2|47-postAction
                //Affichage du mot de passe
                System.out.println(password);
                ni= new PhoneNI();
               ct= new PhoneController(ni, this);
               ni.setPhoneController(ct);
                  ct.initialize();
                ct.sendConnect(Integer.parseInt(password));
            }//GEN-BEGIN:|8-itemCommandAction|3|8-postItemCommandAction
        }//GEN-END:|8-itemCommandAction|3|8-postItemCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|8-itemCommandAction|4|
    //</editor-fold>//GEN-END:|8-itemCommandAction|4|
/*Page d'attente de question(Etat de blocage de l'application) à appeler après avoir répondu*/
    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: waitScreen ">//GEN-BEGIN:|49-getter|0|49-preInit
    /**
     * Returns an initiliazed instance of waitScreen component.
     * @return the initialized component instance
     */
    public WaitScreen getWaitScreen() {
        if (waitScreen == null) {//GEN-END:|49-getter|0|49-preInit
            // Blocking window creation
            waitScreen = new WaitScreen(getDisplay());//GEN-BEGIN:|49-getter|1|49-postInit
            waitScreen.setTitle("iQuizz");
            waitScreen.setCommandListener(this);
            waitScreen.setImage(getImage());
            waitScreen.setText("Attente de questions");
            waitScreen.setTask(getTask());//GEN-END:|49-getter|1|49-postInit
            System.out.println("WaitScreen");

        }//GEN-BEGIN:|49-getter|2|
        return waitScreen;
    }
    //</editor-fold>//GEN-END:|49-getter|2|
public void write(String test)
{
waitScreen.setText(test);
}
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: task ">//GEN-BEGIN:|54-getter|0|54-preInit
/**
 * Returns an initiliazed instance of task component.
 * @return the initialized component instance
 */
public SimpleCancellableTask getTask() {
    if (task == null) {//GEN-END:|54-getter|0|54-preInit
            // write pre-init user code here
        task = new SimpleCancellableTask();//GEN-BEGIN:|54-getter|1|54-execute
        task.setExecutable(new org.netbeans.microedition.util.Executable() {
            public void execute() throws Exception {//GEN-END:|54-getter|1|54-execute
                    // write task-execution user code here
            }//GEN-BEGIN:|54-getter|2|54-postInit
        });//GEN-END:|54-getter|2|54-postInit
            // write post-init user code here
    }//GEN-BEGIN:|54-getter|3|
    return task;
}
//</editor-fold>//GEN-END:|54-getter|3|
/*Méthode qui permet d'avoir l'image pour le WaitScreen*/
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: image ">//GEN-BEGIN:|57-getter|0|57-preInit
/**
 * Returns an initiliazed instance of image component.
 * @return the initialized component instance
 */
public Image getImage() {
    if (image == null) {//GEN-END:|57-getter|0|57-preInit
            // write pre-init user code here
        try {//GEN-BEGIN:|57-getter|1|57-@java.io.IOException
            image = Image.createImage("/iQuizzView/sanglass.png");
        } catch (java.io.IOException e) {//GEN-END:|57-getter|1|57-@java.io.IOException
                e.printStackTrace();
        }//GEN-LINE:|57-getter|2|57-postInit
            // write post-init user code here
    }//GEN-BEGIN:|57-getter|3|
    return image;
}
//</editor-fold>//GEN-END:|57-getter|3|


/*Liste de sélection:*/
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: list ">//GEN-BEGIN:|69-getter|0|69-preInit
/**
 * Returns an initiliazed instance of list component.
 * @return the initialized component instance
 */
public List getList() {
    if (list == null) {//GEN-END:|69-getter|0|69-preInit
            // List display
            System.out.println("getList list null");
            int i = 1;
            list = new List("iQuizz r\u00E9ponses", Choice.MULTIPLE);//GEN-BEGIN:|69-getter|1|69-postInit
            list.addCommand(getOkCommand3());
            list.setCommandListener(this);
            list.setSelectedFlags(new boolean[] {  });//GEN-END:|69-getter|1|69-postInit
            // Responses list display
            while (i< this.responseschoices) {
                System.out.println("List display successful");
                list.append(Integer.toString(i), null);
                i = i + 1;
            }
            System.out.println("List displaying finished");
    }//GEN-BEGIN:|69-getter|2|
    return list;
}
//</editor-fold>//GEN-END:|69-getter|2|
/*Non utilisée*/
//<editor-fold defaultstate="collapsed" desc=" Generated Method: listAction ">//GEN-BEGIN:|69-action|0|69-preAction
/**
 * Performs an action assigned to the selected list element in the list component.
 */
public void listAction() {//GEN-END:|69-action|0|69-preAction
        //Element sélectionné
        System.out.println("Sélection de la liste");
        String __selectedString = getList().getString(getList().getSelectedIndex());//GEN-LINE:|69-action|1|69-postAction

}//GEN-BEGIN:|69-action|2|
//</editor-fold>//GEN-END:|69-action|2|

    /*Commande pour valider le choix des réponses */
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand3 ">//GEN-BEGIN:|76-getter|0|76-preInit
/**
 * Returns an initiliazed instance of okCommand3 component.
 * @return the initialized component instance
 */
public Command getOkCommand3() {
    if (okCommand3 == null) {//GEN-END:|76-getter|0|76-preInit
            // write pre-init user code here
        okCommand3 = new Command("Ok", Command.OK, 0);//GEN-LINE:|76-getter|1|76-postInit

    }//GEN-BEGIN:|76-getter|2|
    return okCommand3;
}
//</editor-fold>//GEN-END:|76-getter|2|







    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

}
